package com.qqt.csr.file.service.impl;

import com.google.common.collect.Lists;
import com.obs.services.ObsClient;
import com.obs.services.model.*;
import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.file.config.HuaWeiObsProperties;
import com.qqt.csr.file.service.IBucketService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class BucketHWOBSServiceImpl extends AbstractHWOBSService  implements IBucketService {

    @Override
    public void createBucket(String bucketName) {
        ServiceAssert.isTrue(StringUtils.isNotBlank(bucketName), StatusCode.Common.NULL_ERROR.getCode(), "桶名称不能为空");
        if (obsClient.headBucket(bucketName)) {
            return;
        }
        CreateBucketRequest request = new CreateBucketRequest();
        request.setBucketName(bucketName);
        request.setLocation(getRegion(huaWeiObsProperties.getEndPoint()));
        ObsBucket bucket = obsClient.createBucket(request);
        ServiceAssert.isTrue(isRequestSuccess(bucket), StatusCode.Common.THIRD_API_ERROR.getCode(), "创建桶失败");

        BucketCorsRule rule = new BucketCorsRule();
        ArrayList<String> allowedOrigin = new ArrayList<String>();
        allowedOrigin.add("*");
        rule.setAllowedOrigin(allowedOrigin);
        ArrayList<String> allowedMethod = new ArrayList<String>();
        allowedMethod.add("GET");
        allowedMethod.add("PUT");
        allowedMethod.add("DELETE");
        allowedMethod.add("POST");
        allowedMethod.add("HEAD");
        rule.setAllowedMethod(allowedMethod);
        ArrayList<String> exposeHeader = new ArrayList<String>();
        exposeHeader.add("x-obs-expose-header");
        rule.setExposeHeader(exposeHeader);
        rule.setMaxAgeSecond(10);
        List<BucketCorsRule> rules = new ArrayList<BucketCorsRule>();
        rules.add(rule);
        BucketCors cors = new BucketCors();
        cors.setRules(rules);
        obsClient.setBucketCors(bucketName, cors);
    }

    @Override
    public void deleteBucket(String bucketName) {
        ServiceAssert.isTrue(StringUtils.isNotBlank(bucketName), StatusCode.Common.NULL_ERROR.getCode(), "桶名称不能为空");
        if (!obsClient.headBucket(bucketName)) {
            return;
        }
        HeaderResponse headerResponse = obsClient.deleteBucket(bucketName);
        ServiceAssert.isTrue(isRequestSuccess(headerResponse), StatusCode.Common.THIRD_API_ERROR.getCode(), "删除桶失败");
    }

}
